package week11;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class FutureTest {

	public static void main(String[] args) throws InterruptedException, ExecutionException {
		/*演示FutureTask*/
        Task task = new Task();
		FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
		ExecutorService executor = Executors.newCachedThreadPool();
		executor.submit(futureTask);
		executor.shutdown();
		
		//new Thread(futureTask).start();//因为实现了Runnable接口，所以也可以这样启动
		
		while(!futureTask.isDone()){
			System.out.println("子线程还没做完，我在做点其他事情");
			TimeUnit.SECONDS.sleep(1);
		}
		try {
			System.out.println("子线程运行的结果："+futureTask.get());
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		/*演示invokeAll*/
		//执行完一组任务，再返回结果
		List<Task> taskList = new ArrayList<>();
		for (int i = 0; i < 2; i++) {
			taskList.add(new Task());
		}
		ExecutorService batchExecutor = Executors.newCachedThreadPool();
		List<Future<Integer>> futureTasks = batchExecutor.invokeAll(taskList);
		batchExecutor.shutdown();
		int count = futureTasks.size();
		int temp = 0;
		while(count!=temp){
			for (Future<Integer> future : futureTasks) {
				if(future.isDone()){
					temp++;
					System.out.println("运行结果为:"+future.get());
				}
			}
			System.out.println("子线程还没做完，我在做点其他事情");
			TimeUnit.SECONDS.sleep(1);
		}
		System.out.println("所有子线程运行结束");
		
	}

}

class Task implements Callable<Integer>{

	@Override
	public Integer call() throws Exception {
		int temp = 0;
		for (int i = 0; i < 100; i++) {
			temp += i;
		}
		TimeUnit.SECONDS.sleep(3);
		return temp;
	}

	
	
}
